package com.ruoyi.qiushi.service.deviceData.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.qiushi.domain.deviceData.TblQsBloodPressureRecord;
import com.ruoyi.qiushi.domain.equipment.QiushiDevice;
import com.ruoyi.qiushi.domain.equipment.QiushiDeviceType;
import com.ruoyi.qiushi.domain.system.QiushiTask;
import com.ruoyi.qiushi.domain.system.QiushiTaskRecord;
import com.ruoyi.qiushi.domain.user.MemberPointRecord;
import com.ruoyi.qiushi.domain.user.MemberUser;
import com.ruoyi.qiushi.domain.user.MemberUserFamily;
import com.ruoyi.qiushi.domain.equipment.QiushiWarning;
import com.ruoyi.qiushi.service.deviceData.ITblQsBloodPressureRecordService;
import com.ruoyi.qiushi.service.equipment.IQiushiDeviceService;
import com.ruoyi.qiushi.service.equipment.IQiushiDeviceTypeService;
import com.ruoyi.qiushi.service.system.IQiushiTaskRecordService;
import com.ruoyi.qiushi.service.system.IQiushiTaskService;
import com.ruoyi.qiushi.service.user.IMemberPointRecordService;
import com.ruoyi.qiushi.service.user.IMemberUserFamilyService;
import com.ruoyi.qiushi.service.user.IMemberUserService;
import com.ruoyi.qiushi.service.equipment.IQiushiWarningService;
import com.ruoyi.system.service.ISysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.qiushi.mapper.deviceData.QiushiDeviceBloodPressureMapper;
import com.ruoyi.qiushi.domain.deviceData.QiushiDeviceBloodPressure;
import com.ruoyi.qiushi.service.deviceData.IQiushiDeviceBloodPressureService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 血压设备数据Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-10
 */
@Service
public class QiushiDeviceBloodPressureServiceImpl implements IQiushiDeviceBloodPressureService {
    private static final Logger log = LoggerFactory.getLogger(QiushiDeviceBloodPressureServiceImpl.class);

    @Autowired
    private QiushiDeviceBloodPressureMapper qiushiDeviceBloodPressureMapper;
    @Autowired
    private IQiushiWarningService warningService;
    @Autowired
    private ITblQsBloodPressureRecordService tblQsBloodPressureRecordService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IQiushiDeviceService deviceService;
    @Autowired
    private IQiushiDeviceTypeService deviceTypeService;
    @Autowired
    private IQiushiTaskService taskService;
    @Autowired
    private IMemberUserFamilyService userFamilyService;
    @Autowired
    private IMemberUserService userService;
    @Autowired
    private IMemberPointRecordService pointRecordService;
    @Autowired
    private IQiushiTaskRecordService taskRecordService;

    /**
     * 查询血压设备数据
     *
     * @param id 血压设备数据主键
     * @return 血压设备数据
     */
    @Override
    public QiushiDeviceBloodPressure selectQiushiDeviceBloodPressureById(Long id) {
        return qiushiDeviceBloodPressureMapper.selectQiushiDeviceBloodPressureById(id);
    }

    /**
     * 查询血压设备数据列表
     *
     * @param qiushiDeviceBloodPressure 血压设备数据
     * @return 血压设备数据
     */
    @Override
    public List<QiushiDeviceBloodPressure> selectQiushiDeviceBloodPressureList(QiushiDeviceBloodPressure qiushiDeviceBloodPressure) {
        return qiushiDeviceBloodPressureMapper.selectQiushiDeviceBloodPressureList(qiushiDeviceBloodPressure);
    }

    /**
     * 获取上周数据
     * @return
     */
    @Override
    public List<QiushiDeviceBloodPressure> lastWeekData(){
        return qiushiDeviceBloodPressureMapper.lastWeekData();
    }

    @Override
    public List<QiushiDeviceBloodPressure> selectLastData(String startTime, String endTime, String deviceNo) {
        return qiushiDeviceBloodPressureMapper.selectLastData(startTime,endTime,deviceNo);
    }

    /**
     * 新增血压设备数据
     *
     * @param qiushiDeviceBloodPressure 血压设备数据
     * @return 结果
     */
    @Override
    public int insertQiushiDeviceBloodPressure(QiushiDeviceBloodPressure qiushiDeviceBloodPressure) {
        qiushiDeviceBloodPressure.setCreateTime(DateUtils.getNowDate());
        return qiushiDeviceBloodPressureMapper.insertQiushiDeviceBloodPressure(qiushiDeviceBloodPressure);
    }

    /**
     * 修改血压设备数据
     *
     * @param qiushiDeviceBloodPressure 血压设备数据
     * @return 结果
     */
    @Override
    public int updateQiushiDeviceBloodPressure(QiushiDeviceBloodPressure qiushiDeviceBloodPressure) {
        qiushiDeviceBloodPressure.setUpdateTime(DateUtils.getNowDate());
        return qiushiDeviceBloodPressureMapper.updateQiushiDeviceBloodPressure(qiushiDeviceBloodPressure);
    }

    /**
     * 批量删除血压设备数据
     *
     * @param ids 需要删除的血压设备数据主键
     * @return 结果
     */
    @Override
    public int deleteQiushiDeviceBloodPressureByIds(Long[] ids) {
        return qiushiDeviceBloodPressureMapper.deleteQiushiDeviceBloodPressureByIds(ids);
    }

    /**
     * 删除血压设备数据信息
     *
     * @param id 血压设备数据主键
     * @return 结果
     */
    @Override
    public int deleteQiushiDeviceBloodPressureById(Long id) {
        return qiushiDeviceBloodPressureMapper.deleteQiushiDeviceBloodPressureById(id);
    }

    /**
     * 获取血压数据
     */
    @Override
    @Transactional
    @DataSource(value = DataSourceType.MASTER)
    public void saveData(List<TblQsBloodPressureRecord> data) {
        if (!data.isEmpty()) {
            List<QiushiDeviceBloodPressure> getData = data.stream().map(record -> {
                QiushiDeviceBloodPressure pressure = new QiushiDeviceBloodPressure();
                BeanUtils.copyProperties(record, pressure);
                pressure.setCreateBy(null);
                pressure.setId(null);
                pressure.setSourceId(record.getId());

                QiushiDevice device = deviceService.getDeviceByDeviceNo(record.getEid());
                QiushiDeviceType deviceType = deviceTypeService.selectQiushiDeviceTypeById(2L);
                JSONObject deviceStandard = JSONObject.parse(deviceType.getDeviceStandard());//设备指标

                if (Objects.nonNull(device) && Objects.nonNull(device.getFamilyId())) {

                    //查询与设备有关联的用户
                    MemberUserFamily params = new MemberUserFamily();
                    params.setDelFlag("0");
                    params.setFamilyId(device.getFamilyId());
                    List<MemberUserFamily> memberUserFamilies = userFamilyService.selectMemberUserFamilyList(params);

                    //上传数据任务
                    for (MemberUserFamily memberUserFamily : memberUserFamilies) {
                        List<QiushiTask> taskList = taskService.getNotFinishTaskByFlag("data",memberUserFamily.getUserId());
                        for (QiushiTask task : taskList) {
                            BigDecimal reward = task.getPoint();//获取奖励
                            if(reward.compareTo(BigDecimal.ZERO)>0){
                                MemberUser user = userService.selectMemberUserById(memberUserFamily.getUserId());
                                if(Objects.nonNull(user)){
                                    user.setPoint(user.getPoint().add(reward));
                                    userService.updateMemberUser(user);

                                    String title = task.getName();
                                    //添加积分记录
                                    MemberPointRecord pointRecord = new MemberPointRecord();
                                    pointRecord.setUserId(user.getId());
                                    pointRecord.setTitle(title);
                                    pointRecord.setDescription(title);
                                    pointRecord.setPoint(reward);
                                    pointRecord.setTotalPoint(user.getPoint());
                                    pointRecord.setCreateTime(new Date());
                                    pointRecord.setUpdateTime(new Date());
                                    pointRecordService.insertMemberPointRecord(pointRecord);

                                    QiushiTaskRecord taskRecord = new QiushiTaskRecord();
                                    taskRecord.setTaskId(task.getId());
                                    taskRecord.setUserId(user.getId());
                                    taskRecord.setCreateTime(new Date());
                                    taskRecord.setUpdateTime(new Date());
                                    taskRecordService.insertQiushiTaskRecord(taskRecord);

                                }

                            }
                        }
                    }

                    //判断用户设备是否已经到期
                    Date serviceEndDate = device.getServiceEndDate();
                    if (Objects.isNull(serviceEndDate)) { //设备没有购买服务
                        log.info("未购买设备服务");
                        return pressure;
                    }
                    if (serviceEndDate.before(new Date())) {//设备过期
                        log.info("设备服务过期");
                        return pressure;
                    }
                    //是否定制预警
                    if (StringUtils.isNotBlank(device.getDeviceStandard())) {
                        deviceStandard = JSONObject.parse(device.getDeviceStandard());
                    }
                    if (this.standard(deviceStandard, record.getShrink(), record.getDiastole(), record.getHeartRate())) {
                        //预警
                        QiushiWarning warning = new QiushiWarning();
                        warning.setFamilyId(device.getFamilyId());
                        warning.setDeviceId(device.getId());
                        warning.setDeviceType(device.getDeviceType());
                        warning.setDataId(record.getId());
                        warning.setWarningName("血压异常提示");
                        warning.setWarningContent("您的血压指标异常，请立即注意预防，等待医生联系复查。");
                        warning.setStatus("1");
                        warningService.insertQiushiWarning(warning);
                    }
                }
                return pressure;
            }).collect(Collectors.toList());

            qiushiDeviceBloodPressureMapper.saveBatch(getData);
        }

    }


    /**
     * 判断是否要预警
     *
     * @param deviceStandard
     * @param sbp            收缩压
     * @param dbp            舒张压
     * @param heartRate
     * @return
     */
    private boolean standard(JSONObject deviceStandard, String sbp, String dbp, String heartRate) {
        //判断指标是否正常
        //收缩压（高压）
        if (deviceStandard.containsKey("sbp")) {
            if (StringUtils.isNotBlank(sbp)) {
                int value = Integer.parseInt(sbp);
                JSONObject standard = deviceStandard.getJSONObject("sbp");
                if (standard.containsKey("max")) {
                    Integer max = standard.getInteger("max");
                    if (Objects.nonNull(max) && value >= max) {
                        return true;
                    }
                }
                if (standard.containsKey("min")) {
                    Integer min = standard.getInteger("min");
                    if (Objects.nonNull(min) && value <= min) {
                        return true;
                    }
                }
            }
        }
        //舒张压（低压）
        if (deviceStandard.containsKey("dbp")) {
            if (StringUtils.isNotBlank(dbp)) {
                int value = Integer.parseInt(dbp);
                JSONObject standard = deviceStandard.getJSONObject("dbp");
                if (standard.containsKey("max")) {
                    Integer max = standard.getInteger("max");
                    if (Objects.nonNull(max) && value >= max) {
                        return true;
                    }
                }
                if (standard.containsKey("min")) {
                    Integer min = standard.getInteger("min");
                    if (Objects.nonNull(min) && value <= min) {
                        return true;
                    }
                }
            }
        }
        //脉率
        if (deviceStandard.containsKey("heart_rate")) {
            if (StringUtils.isNotBlank(heartRate)) {
                int value = Integer.parseInt(heartRate);
                JSONObject standard = deviceStandard.getJSONObject("heart_rate");
                if (standard.containsKey("max")) {
                    Integer max = standard.getInteger("max");
                    if (Objects.nonNull(max) && value >= max) {
                        return true;
                    }
                }
                if (standard.containsKey("min")) {
                    Integer min = standard.getInteger("min");
                    if (Objects.nonNull(min) && value <= min) {
                        return true;
                    }
                }
            }
        }

        return false;
    }
}
